/* eslint-disable array-callback-return */
/* eslint-disable guard-for-in */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react-hooks/rules-of-hooks */
import { getFetch, doFetch } from '@/utils/doFetch';
import { ProTable } from '@ant-design/pro-components';
import { useLocation, useModel } from '@umijs/max';
import { memo, useEffect, useRef, useState } from 'react';
import { Dropdown, Button } from "antd";


const Mtable = (props) => {
  const {
    actionRef, //表格动作
    formRef, //表单Ref
    rowKey = 'id', // key
    columns = [], //columns
    style, //style
    path, //接口地址
    extraparams = {}, //额外参数
    pageSize, //修改默认pageSize
    pagination = true, //分页设置
    actions, //横向滚动
    method = 'get', //
    getDefaultSelected, //存在默认选中向上返回选中值
    dataSource,
    toolBarRender,
    search,
    isShowpagesizeoptions = true, //是否显示可以修改size的
  } = props;

  //消息推送更新页面数据
  const {
    initialState: { effectTables },
    setInitialState,
  } = useModel('@@initialState');
  const [formval, setFormval] = useState({});
  const [columnes, setcolumnes] = useState(columns ?? []);

  const actionRefs = actionRef ?? useRef(),
    ifspagination = pagination === 'false' || pagination === false,
    [size, setsize] = useState(localStorage.getItem('SIZE') ?? 'small');

  //调用接口
  const request = async (params) => {
    if (dataSource) return dataSource;
    let newparams = {
      ...params,
      pageIndex: params.current,
      pageSize: params.pageSize || pageSize,
    };

    delete newparams.current;
    delete newparams.refresh;
    if (ifspagination) {
      delete newparams.pageIndex;
      delete newparams.pageSize;
    }
    const result = method === 'post' ? await doFetch({ url: path, params: newparams }) : await getFetch({ url: path, params: newparams });
    //分页结果
    let data = result?.data?.page?.records,
      success = true,
      total = result?.data?.page?.total;
    //不带分页获取结果
    if (ifspagination) {
      data = result?.data?.dataList;
      total = result?.data?.dataList?.length;
    }
    //存在默认选中向上返回选中值
    getDefaultSelected && getDefaultSelected(result?.data);

    return {
      data,
      success,
      total,
    };
  };

  //更新 columns
  useEffect(() => {
    setcolumnes(() => {
      return columns.map((it, index) => {
        let options = {};
        if (!it.render) {
          options = {
            render: (text, row) => {
              return (
                <span title={row[it.dataIndex]} className="table-cell">
                  {row[it.dataIndex] ?? '-'}
                </span>
              );
            },
          };
        }
        if (
          it.valueType === "select" ||
          it.valueType === "checkbox" ||
          it.valueType === "treeSelect"
        ) {

          if (Array.isArray(it.options)) {
            options = {
              fieldProps: {
                options: [...it.options],
              },
            };
          } else if (it.options) {
            options = {
              request: async (params) => {
                let list = await getFetch({
                  url: it?.options?.path,
                  params: it?.options?.params,
                });
                const res = list.data.dataList;
                return res;
              },
            };
          }
        }
        return {
          ...it,
          ...options,
          key: it.searchKey ?? it?.key,
          valueType: it.searchValueType ?? it?.valueType,
        };
      });
    });
  }, [columns]);


  return (
    <div>
      {props?.headerTitle && <h2 className='ltitle' style={{ margin: "0 0 12px 0" }}>{props?.headerTitle}</h2>}
      <ProTable
        {...props}
        toolBarRender={toolBarRender === false ? toolBarRender : () => actions ?? <div></div>}
        request={request}
        params={{ ...extraparams }}
        size={size}
        columns={
          columnes?.filter?.(
            (it) => ['split', 'nosubmit'].indexOf(it.valueType) === -1,
          ) ?? []
        }
        style={style || {}}
        actionRef={actionRefs}
        rowKey={rowKey} //表格每行数据的key
        dateFormatter="string"
        scroll={{
          y: 'calc(100vh - 360px)',
        }}
        pagination={
          pagination
            ? {
              showTotal: (total) => <span>共{total}条</span>,
              showQuickJumper: true,
              showSizeChanger: isShowpagesizeoptions === 'false' ? false : true,
              pageSizeOptions: [5, 10, 15, 30, 50, 100, 200],
              defaultPageSize: pageSize || 15,
            }
            : false
        }
        search={search === false ? search : {
          //filterType: 'light', //轻量模式
          placement: 'bottomLeft',
          span: {
            xs: 24,
            sm: 12,
            md: 8,
            lg: 8,
            xl: 6,
            xxl: 6,
          }
        }}
      />

    </div>

  );
};
export default memo(Mtable);
